// src/screens/EditProfileScreen.js
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, Image, ScrollView, StyleSheet, Alert, Platform } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import api from '../services/api';
import { setUserInfo } from '../store/userSlice';

// 只在平台支持时才导入DateTimePicker
let DateTimePickerComponent = null;
try {
  const DateTimePicker = require('@react-native-community/datetimepicker').default;
  DateTimePickerComponent = DateTimePicker;
} catch (e) {
  console.log('DateTimePicker not available:', e);
}

const EditProfileScreen = ({ navigation }) => {
  const userInfo = useSelector(state => state.user.userInfo);
  const dispatch = useDispatch();
  const [photos, setPhotos] = useState([]);
  const [introduction, setIntroduction] = useState('');
  const [personality, setPersonality] = useState('');
  const [purpose, setPurpose] = useState('');
  const [height, setHeight] = useState('');
  const [occupation, setOccupation] = useState('');
  const [education, setEducation] = useState('');
  const [school, setSchool] = useState('');
  const [from, setFrom] = useState('');
  const [pet, setPet] = useState('');
  const [lifestyle, setLifestyle] = useState({
    fitness: false,
    drinking: false,
    smoking: false
  });
  const [assets, setAssets] = useState({
    income: '',
    car: '',
    house: ''
  });
  const [tags, setTags] = useState([]);
  const [nickname, setNickname] = useState('');
  const [birthday, setBirthday] = useState(new Date());
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [gender, setGender] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // 初始化用户数据
    if (userInfo) {
      setNickname(userInfo.nickname || userInfo.name || '');
      if (userInfo.birthday) {
        // 确保birthday是Date对象
        const birthdayDate = new Date(userInfo.birthday);
        if (!isNaN(birthdayDate.getTime())) {
          setBirthday(birthdayDate);
        }
      }
      setGender(userInfo.gender || '');
      setPhotos(userInfo.photos || []);
      setIntroduction(userInfo.introduction || '');
      setPersonality(userInfo.personality || '');
      setPurpose(userInfo.purpose || '');
      setHeight(userInfo.height?.toString() || '');
      setOccupation(userInfo.occupation || '');
      setEducation(userInfo.education || '');
      setSchool(userInfo.school || '');
      setFrom(userInfo.from || '');
      setPet(userInfo.pet || '');
      
      if (userInfo.lifestyle) {
        setLifestyle(userInfo.lifestyle);
      }
      
      if (userInfo.assets) {
        setAssets(userInfo.assets);
      }
      
      if (userInfo.tags) {
        setTags(userInfo.tags);
      }
    }
  }, [userInfo]);

  const addPhoto = () => {
    if (photos.length >= 9) {
      Alert.alert('提示', '最多只能添加9张照片');
      return;
    }
    // 模拟添加照片
    const newPhoto = `https://picsum.photos/200/200?random=${photos.length + 1}`;
    setPhotos([...photos, newPhoto]);
  };

  const removePhoto = (index) => {
    const newPhotos = [...photos];
    newPhotos.splice(index, 1);
    setPhotos(newPhotos);
  };

  const toggleLifestyle = (key) => {
    setLifestyle({
      ...lifestyle,
      [key]: !lifestyle[key]
    });
  };

  const onDateChange = (event, selectedDate) => {
    const currentDate = selectedDate || birthday;
    if (Platform.OS === 'android') {
      // Android上隐藏日期选择器
      setShowDatePicker(false);
    }
    setBirthday(currentDate);
  };

  const showDatepicker = async () => {
    if (Platform.OS === 'android' && DateTimePickerComponent) {
      // 在Android上直接显示日期选择器
      setShowDatePicker(true);
    } else if (Platform.OS === 'ios' && DateTimePickerComponent) {
      // 在iOS上显示日期选择器
      setShowDatePicker(true);
    } else {
      // 如果没有日期选择器组件，显示一个提示
      Alert.alert('提示', '请选择日期', [
        {
          text: '确定',
          onPress: () => setShowDatePicker(true)
        }
      ]);
    }
  };

  const formatDate = (date) => {
    if (!(date instanceof Date)) return '';
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const saveProfile = async () => {
    setLoading(true);
    try {
      const profileData = {
        nickname,
        birthday: formatDate(birthday),
        gender,
        photos,
        introduction,
        personality,
        purpose,
        height: height ? parseInt(height) : null,
        occupation,
        education,
        school,
        from,
        pet,
        lifestyle,
        assets,
        tags
      };

      const response = await api.updateUserProfile(profileData);
      if (response.success) {
        Alert.alert('成功', '个人资料已保存');
        // 更新 Redux 中的用户信息
        dispatch(setUserInfo(response.data));
        navigation.goBack();
      } else {
        Alert.alert('错误', response.message || '保存失败');
      }
    } catch (error) {
      Alert.alert('错误', '保存失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Text style={styles.cancelButton}>取消</Text>
        </TouchableOpacity>
        <Text style={styles.title}>编辑资料</Text>
        <TouchableOpacity onPress={saveProfile} disabled={loading}>
          <Text style={[styles.saveButton, loading && styles.disabledButton]}>
            {loading ? '保存中...' : '保存'}
          </Text>
        </TouchableOpacity>
      </View>

      {/* 照片上传区域 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>照片 (最多9张)</Text>
        <View style={styles.photoGrid}>
          {photos.map((photo, index) => (
            <View key={index} style={styles.photoContainer}>
              <Image source={{ uri: photo }} style={styles.photo} />
              <TouchableOpacity 
                style={styles.removePhotoButton} 
                onPress={() => removePhoto(index)}
              >
                <Text style={styles.removePhotoText}>✕</Text>
              </TouchableOpacity>
            </View>
          ))}
          {photos.length < 9 && (
            <TouchableOpacity style={styles.addPhotoButton} onPress={addPhoto}>
              <Text style={styles.addPhotoText}>+</Text>
            </TouchableOpacity>
          )}
        </View>
      </View>

      {/* 基本信息 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>基本信息</Text>
        
        <View style={styles.formGroup}>
          <Text style={styles.label}>昵称</Text>
          <TextInput 
            value={nickname} 
            onChangeText={setNickname} 
            style={styles.input} 
            placeholder="请输入昵称"
          />
        </View>

        <View style={styles.formGroup}>
          <Text style={styles.label}>生日</Text>
          <TouchableOpacity onPress={showDatepicker} style={styles.dateInput}>
            <Text style={styles.dateText}>{formatDate(birthday)}</Text>
          </TouchableOpacity>
          {showDatePicker && DateTimePickerComponent && (
            <DateTimePickerComponent
              testID="dateTimePicker"
              value={birthday}
              mode={'date'}
              is24Hour={true}
              display="default"
              onChange={onDateChange}
            />
          )}
        </View>

        <View style={styles.formGroup}>
          <Text style={styles.label}>性别</Text>
          <View style={styles.optionsContainer}>
            {['男', '女', '其他'].map((option) => (
              <TouchableOpacity
                key={option}
                style={[
                  styles.optionButton,
                  gender === option && styles.selectedOption
                ]}
                onPress={() => setGender(option)}
              >
                <Text style={[
                  styles.optionText,
                  gender === option && styles.selectedOptionText
                ]}>
                  {option}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      </View>

      {/* 自我介绍 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>自我介绍</Text>
        <TextInput 
          value={introduction} 
          onChangeText={setIntroduction} 
          multiline 
          numberOfLines={4} 
          style={[styles.input, styles.textArea]} 
          placeholder="介绍一下你自己..."
        />
      </View>

      {/* 我的性格 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>我的性格</Text>
        <TextInput 
          value={personality} 
          onChangeText={setPersonality} 
          style={styles.input} 
          placeholder="描述一下你的性格特点"
        />
      </View>

      {/* 交友目的 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>交友目的</Text>
        <TextInput 
          value={purpose} 
          onChangeText={setPurpose} 
          style={styles.input} 
          placeholder="你想通过交友获得什么"
        />
      </View>

      {/* 详细信息 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>详细信息</Text>
        
        <View style={styles.formGroup}>
          <Text style={styles.label}>身高 (cm)</Text>
          <TextInput 
            value={height} 
            onChangeText={setHeight} 
            style={styles.input} 
            placeholder="例如: 175"
            keyboardType="numeric"
          />
        </View>

        <View style={styles.formGroup}>
          <Text style={styles.label}>职业</Text>
          <TextInput 
            value={occupation} 
            onChangeText={setOccupation} 
            style={styles.input} 
            placeholder="你的职业"
          />
        </View>

        <View style={styles.formGroup}>
          <Text style={styles.label}>学历</Text>
          <TextInput 
            value={education} 
            onChangeText={setEducation} 
            style={styles.input} 
            placeholder="你的学历"
          />
        </View>

        <View style={styles.formGroup}>
          <Text style={styles.label}>学校</Text>
          <TextInput 
            value={school} 
            onChangeText={setSchool} 
            style={styles.input} 
            placeholder="你就读的学校"
          />
        </View>

        <View style={styles.formGroup}>
          <Text style={styles.label}>来自</Text>
          <TextInput 
            value={from} 
            onChangeText={setFrom} 
            style={styles.input} 
            placeholder="你的家乡"
          />
        </View>

        <View style={styles.formGroup}>
          <Text style={styles.label}>宠物</Text>
          <TextInput 
            value={pet} 
            onChangeText={setPet} 
            style={styles.input} 
            placeholder="你养的宠物"
          />
        </View>
      </View>

      {/* 生活习惯 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>生活习惯</Text>
        <View style={styles.habitsContainer}>
          <TouchableOpacity 
            style={[styles.habitButton, lifestyle.fitness && styles.selectedHabit]} 
            onPress={() => toggleLifestyle('fitness')}
          >
            <Text style={[styles.habitText, lifestyle.fitness && styles.selectedHabitText]}>
              健身
            </Text>
          </TouchableOpacity>
          
          <TouchableOpacity 
            style={[styles.habitButton, lifestyle.drinking && styles.selectedHabit]} 
            onPress={() => toggleLifestyle('drinking')}
          >
            <Text style={[styles.habitText, lifestyle.drinking && styles.selectedHabitText]}>
              饮酒
            </Text>
          </TouchableOpacity>
          
          <TouchableOpacity 
            style={[styles.habitButton, lifestyle.smoking && styles.selectedHabit]} 
            onPress={() => toggleLifestyle('smoking')}
          >
            <Text style={[styles.habitText, lifestyle.smoking && styles.selectedHabitText]}>
              吸烟
            </Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* 我的资产 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>我的资产</Text>
        
        <View style={styles.formGroup}>
          <Text style={styles.label}>年收入</Text>
          <TextInput 
            value={assets.income} 
            onChangeText={(text) => setAssets({...assets, income: text})} 
            style={styles.input} 
            placeholder="例如: 20万-50万"
          />
        </View>

        <View style={styles.formGroup}>
          <Text style={styles.label}>车产</Text>
          <TextInput 
            value={assets.car} 
            onChangeText={(text) => setAssets({...assets, car: text})} 
            style={styles.input} 
            placeholder="例如: 有车/无车"
          />
        </View>

        <View style={styles.formGroup}>
          <Text style={styles.label}>房产</Text>
          <TextInput 
            value={assets.house} 
            onChangeText={(text) => setAssets({...assets, house: text})} 
            style={styles.input} 
            placeholder="例如: 有房/无房"
          />
        </View>
      </View>

      {/* 个性标签 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>我的个性标签</Text>
        <TextInput 
          value={tags.join(', ')} 
          onChangeText={(text) => setTags(text.split(',').map(t => t.trim()).filter(t => t))} 
          style={styles.input} 
          placeholder="用逗号分隔多个标签，例如: 幽默, 开朗, 体贴"
        />
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 15,
    backgroundColor: '#2196F3',
  },
  cancelButton: {
    color: 'white',
    fontSize: 16,
  },
  title: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
  saveButton: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
  disabledButton: {
    opacity: 0.6,
  },
  section: {
    backgroundColor: 'white',
    padding: 15,
    marginVertical: 5,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333',
  },
  photoGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  photoContainer: {
    position: 'relative',
    margin: 5,
  },
  photo: {
    width: 80,
    height: 80,
    borderRadius: 8,
  },
  removePhotoButton: {
    position: 'absolute',
    top: -8,
    right: -8,
    backgroundColor: 'rgba(0,0,0,0.5)',
    width: 24,
    height: 24,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
  removePhotoText: {
    color: 'white',
    fontSize: 14,
  },
  addPhotoButton: {
    width: 80,
    height: 80,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#ccc',
    justifyContent: 'center',
    alignItems: 'center',
    margin: 5,
  },
  addPhotoText: {
    fontSize: 30,
    color: '#ccc',
  },
  formGroup: {
    marginBottom: 15,
  },
  label: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 5,
    color: '#333',
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    backgroundColor: 'white',
  },
  dateInput: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    backgroundColor: 'white',
    justifyContent: 'center',
  },
  dateText: {
    fontSize: 16,
    color: '#333',
  },
  textArea: {
    height: 100,
    textAlignVertical: 'top',
  },
  optionsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  optionButton: {
    flex: 1,
    padding: 10,
    marginHorizontal: 5,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    alignItems: 'center',
  },
  selectedOption: {
    backgroundColor: '#2196F3',
    borderColor: '#2196F3',
  },
  optionText: {
    color: '#666',
  },
  selectedOptionText: {
    color: 'white',
  },
  habitsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  habitButton: {
    flex: 1,
    padding: 10,
    marginHorizontal: 5,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    alignItems: 'center',
  },
  selectedHabit: {
    backgroundColor: '#2196F3',
    borderColor: '#2196F3',
  },
  habitText: {
    color: '#666',
  },
  selectedHabitText: {
    color: 'white',
  },
});

export default EditProfileScreen;